package com.somlsis.fragment

import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import com.base.AppConfig
import com.base.BaseFragment
import com.clj.fastble.BleManager
import com.event.BindingDeviceEvent
import com.event.MessageEvent
import com.net.HttpResponse
import com.orhanobut.logger.Logger
import com.somlsis.R
import com.somlsis.activity.AddDeviceActivity
import com.somlsis.adapter.DeviceAdapter
import com.somlsis.bean.Device
import com.somlsis.bean.DeviceInfo
import com.somlsis.databinding.FragmentDeviceBinding
import com.somlsis.dialog.BluetoothHintDialog
import com.yanzhenjie.recyclerview.SwipeMenu
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import org.greenrobot.eventbus.Subscribe
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class DeviceFragment : BaseFragment<FragmentDeviceBinding>() {
    private lateinit var deviceAdapter: DeviceAdapter
    override fun getViewBinding(): FragmentDeviceBinding {
        return FragmentDeviceBinding.inflate(layoutInflater)
    }

    private var launcher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        //处理返回的结果
        val code = result.resultCode //返回码 如：Activity.RESULT_OK、Activity.RESULT_CANCELED
        val data = result.data
        data?.let {
            val deviceMac = it.getStringExtra("device_mac")

            deviceMac?.let { mac ->
                Logger.d("device_mac:$deviceMac")
                deviceAdapter.addData(
                    Device(
                        BleManager.getInstance().bluetoothAdapter.getRemoteDevice(
                            deviceMac
                        )
                    )
                )
            }
        }


    }

    override fun createView() {
        binding.phonePermissionSettings.setOnClickListener {
            //跳转应用消息，间接打开应用权限设置-效率高
            //跳转应用消息，间接打开应用权限设置-效率高
            val intent = Intent()
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            val uri = Uri.fromParts("package", context?.let { it.packageName }, null)
            intent.data = uri
            startActivity(intent)
        }
        binding.deviceRv.setSwipeMenuCreator(object : SwipeMenuCreator {
            override fun onCreateMenu(leftMenu: SwipeMenu?, rightMenu: SwipeMenu?, position: Int) {
                val deleteItem = SwipeMenuItem(context)
                deleteItem.setImage(R.mipmap.icon_del)
                // 各种文字和图标属性设置。
                leftMenu?.let {
                    it.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
                }
            }

        })
        binding.deviceRv.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge?.let {
                it.closeMenu()
                deviceAdapter.removeData(adapterPosition)
            }
        }
        context?.let {

            deviceAdapter = DeviceAdapter(it, object : DeviceAdapter.OnDeviceClickListener {
                override fun onItemClick(position: Int, data: Device?) {
                    data?.let { device ->
                        deviceCenter.connectDevice(device)
                        device.isConnect = true
                        deviceAdapter.notifyItemChanged(position)
                    }
                }

                override fun onAddViewClick() {
                    if (deviceCenter.bleManager.isBlueEnable) {
                        /*蓝牙未打开*/
                        val dialog = BluetoothHintDialog(object :
                            BluetoothHintDialog.OnBluetoothButtonClickListener {
                            override fun onGoToSettingsClick() {
                                val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
                                startActivity(intent)
                            }

                            override fun onCancelClick() {

                            }

                        })
                    } else {
                        launcher.launch(Intent(activity, AddDeviceActivity::class.java))
                    }

                }

            })
            binding.deviceRv.adapter = deviceAdapter
        }

    }

    override fun refreshUI() {

    }
    fun getBindingDevice(){
        dataCenter.getBindingDevice(object : Callback<HttpResponse<ArrayList<DeviceInfo>>> {
            override fun onResponse(
                call: Call<HttpResponse<ArrayList<DeviceInfo>>>,
                response: Response<HttpResponse<ArrayList<DeviceInfo>>>
            ) {
                if (response.code() == AppConfig.SUCCEED_CODE) {
                    val body = response.body()
                    body?.let {
                        val dataList = it.data
                        var deviceList = ArrayList<Device>()
                        for (data in dataList) {
                            deviceList.add(
                                Device(
                                    BleManager.getInstance().bluetoothAdapter.getRemoteDevice(
                                        data.serial_mac,
                                    ), data
                                )
                            )
                        }
                        deviceAdapter.setData(deviceList)

                    }
                }
            }

            override fun onFailure(call: Call<HttpResponse<ArrayList<DeviceInfo>>>, t: Throwable) {
            }

        })
    }
    @Subscribe
    fun onBindingDeviceEvent(event: BindingDeviceEvent) {
        getBindingDevice()
    }

}